package com.lbc.service.impl;

import com.github.pagehelper.PageHelper;
import com.lbc.bean.dto.KidDTO;
import com.lbc.bean.dto.KidSearchDTO;
import com.lbc.bean.dto.KidUpdateDTO;
import com.lbc.bean.entity.Kid;
import com.lbc.bean.entity.KidAssist;
import com.lbc.bean.entity.User;
import com.lbc.bean.pojo.Page;
import com.lbc.bean.vo.KidVO;
import com.lbc.bean.vo.OrganizationVO;
import com.lbc.bean.vo.SchoolInfoVO;
import com.lbc.common.constants.Constants;
import com.lbc.common.enums.RoleEnum;
import com.lbc.common.exception.CustomException;
import com.lbc.common.utils.JwtUtils;
import com.lbc.dao.custom.*;
import com.lbc.service.KidService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xyl
 * @date 2021-03-25 14:51
 */
@Service
public class KidServiceImpl implements KidService {
    @Autowired
    private CtKidMapper kidMapper;
    @Autowired
    private CtUserMapper userMapper;
    @Autowired
    private CtKidAssistMapper kidAssistMapper;
    @Autowired
    private CtOrganizationMapper organizationMapper;
    @Autowired
    private CtSchoolMapper schoolMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(KidDTO kidDTO) {
        Integer userId = JwtUtils.getUserId();
        //添加父母
        User user = new User();
        user.setEmail(kidDTO.getParentEmail());
        user.setState(1);
        user.setRoleId(Constants.ROLE_PARENTS);
        user.setCreateBy(userId);
        user.setCreateTime(new Date());
        user.setPassword("123456");
        user.setPhoneNumber(kidDTO.getParentPhoneNumber());
        user.setUsername(kidDTO.getParentName());
        user.setRealName(kidDTO.getParentName());
        int insert = userMapper.insert(user);
        //添加儿童,并关联学校
        Kid kid = new Kid();
        BeanUtils.copyProperties(kidDTO, kid);
        User curUser = (User) SecurityUtils.getSubject().getPrincipal();
        if(Constants.ROLE_SCHOOL == curUser.getRoleId()){
            kid.setSchoolId(schoolMapper.selectByUserId(curUser.getUserId()).getSchoolId());
        }
        kid.setCreateTime(new Date());
        kid.setParentId(user.getUserId());
        kid.setCreateBy(userId);
        kid.setIsDelete(false);
        int roleId = userMapper.selectRoleIdByUserId(userId);
        if (Constants.ROLE_ADMIN == roleId) {
            kid.setSchoolId(kid.getSchoolId());
        } else if(RoleEnum.ROLE_SCHOOL.getType() == roleId){
            //学校角色时
            SchoolInfoVO schoolInfoVO = schoolMapper.selectByUserId(userId);
            kid.setSchoolId(schoolInfoVO.getSchoolId());
        }else{
            CustomException.cast("权限不足！");
        }
        int insert1 = kidMapper.insert(kid);
        //关联帮扶
        for (Integer orgId : kidDTO.getOrgIds()) {
            KidAssist ka = new KidAssist();
            ka.setAssistTo(kid.getKidId());
            ka.setAssistBy(orgId);
            ka.setCreateTime(new Date());
            kidAssistMapper.insert(ka);
        }
        return insert1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modify(KidUpdateDTO kidDTO) {
        Kid sk = kidMapper.selectByPrimaryKey(kidDTO.getKidId());
        kidDTO.getKidId();
        Kid kid = new Kid();
        BeanUtils.copyProperties(kidDTO, kid);
        kid.setUpdateTime(new Date());
        kid.setUpdateBy(JwtUtils.getUserId());
        int i = kidMapper.updateByPrimaryKeySelective(kid);
        //修改父母姓名
        if (StringUtils.isNotBlank(kidDTO.getParentName())) {
            User user = new User();
            user.setUsername(kidDTO.getParentName());
            user.setUserId(sk.getParentId());
            user.setPhoneNumber(kidDTO.getParentPhoneNumber());
            user.setEmail(kidDTO.getParentEmail());
            userMapper.updateByPrimaryKeySelective(user);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(Integer kidId) {
        Kid kid = kidMapper.selectByPrimaryKey(kidId);
        int i = kidMapper.updateIsDelete(kidId);
        User user = new User();
        user.setState(-1);
        user.setUserId(kid.getParentId());
        userMapper.updateByPrimaryKeySelective(user);
        return i;
    }

    @Override
    public KidVO get(Integer kidId) {
        KidVO kidVO = kidMapper.selectKidVO(kidId);
        List<OrganizationVO> organizations = organizationMapper.selectByKidId(Collections.singletonList(kidVO.getKidId()));
        kidVO.setLo(organizations);
        return kidVO;
    }

    @Override
    public List<KidVO> listFront(String searchKey) {
        //只根据儿童姓名模糊搜索
        KidSearchDTO dto = new KidSearchDTO();
        dto.setSearchKidName(searchKey);
        return loadOrg(kidMapper.selectList(dto));
    }

    @Override
    public List<KidVO> listBack(KidSearchDTO dto) {
        Integer userId = JwtUtils.getUserId();
        int roleId = userMapper.selectRoleIdByUserId(userId);
        if (roleId != Constants.ROLE_ADMIN) {
            dto.setState(null);
            dto.setSearchSchoolName(null);
            dto.setRoleId(null);
            dto.setSchoolId(null);
        } else {
            if (ObjectUtils.isNotEmpty(dto.getState()) && 1 == dto.getState()) {
                dto.setUserId(userId);
            }
        }
        if (roleId == Constants.ROLE_PARENTS) {
            //父母只能搜索自己的儿童
            dto.setParentId(userId);
        } else if (roleId != Constants.ROLE_ADMIN) {
            //其他角色只能搜索自己的 , 和只能模糊查询姓名
            dto.setUserId(userId);
        }
        return loadOrg(kidMapper.selectList(dto));
    }

    @Override
    public List<KidVO> getBySchoolId(Page page, Integer schoolId) {
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        return loadOrg(kidMapper.selectBySchoolId(schoolId,page.getSearchKey()));
    }


    private List<KidVO> loadOrg(List<KidVO> kidVOS) {
        if (null != kidVOS && kidVOS.size() > 0) {
            List<Integer> collect = kidVOS.stream().map(KidVO::getKidId).collect(Collectors.toList());
            List<OrganizationVO> organizations = organizationMapper.selectByKidId(collect);
            kidVOS.forEach(kid -> {
                kid.setLo(organizations.stream().filter(o -> o.getKidId().equals(kid.getKidId())).collect(Collectors.toList()));
            });
        }
        return kidVOS;
    }
}
